<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>H5拖拽功能</title>
  </head>
  <style>
    .parent {
      height: 200px;
      border: 1px solid cyan;
      margin: 0 auto;
    }
    .child {
      width: 100px;
      height: 100px;
      border: 1px solid red;
      float: left;
      margin: 10px;
    }
    body {
      height: 400px;
    }
  </style>
  <body>
    <div class="parent" id="parent" draggable="true"></div>
    <div>
      <div id="test">数据项：</div>
      <div class="child" draggable="true" id="one">1</div>
      <div class="child" draggable="true" id="two">2</div>
      <div class="child" draggable="true" id="three">3</div>
      <div class="child" draggable="true" id="four">4</div>
    </div>
  </body>
  <script>
    window.onload = function () {
      var parent = document.querySelector(".parent");
      var childs = document.querySelectorAll(".child");
      childs = Array.from(childs);
      childs.forEach(function (item) {
        //拖放对象
        //拖放事件
        //开始拖放
        item.ondragstart = function (event) {
          event.dataTransfer.setData("id", item.id);
        };
        //正在拖放的事件
        item.ondrag = function () {
          // console.log('ondrag');
          item.style.background = 'red'
        };
        //拖放结束
        item.ondragend = function () {
          // console.log('ondragend');
          item.style.background = '#ffffff'
        };
        //拖放经过
        item.ondragover = function () {
          // console.log('ondragend');
          item.style.border = '1px solid cyan'
        };
        //拖放经过
        item.ondragleave = function () {
          // console.log('ondragend');
          item.removeAttribute('style')
        };
      });

      //放置对象事件
      //将拖放元素 拖放放置 对象中
      // 进入目标元素
      parent.ondragenter = function (event) {};

      // 在目标元素内活动
      parent.ondragover = function () {
        //取消事件默认行为
        event.preventDefault();
      };

      // 将拖放元素放置到目标元素内
      parent.ondrop = function (event) {
        console.log("ondrop");
        var id = event.dataTransfer.getData("id");
        var dom = document.querySelector("#" + id);
        this.appendChild(dom);
        event.stopPropagation();
      };

      document.body.ondragover = function (event) {
        event.preventDefault();
      };

      document.body.ondrop = function (event) {
        var id = event.dataTransfer.getData("id");
        var dom = document.querySelector("#" + id);
        this.appendChild(dom);
      };
    };
  </script>
</html>
